package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.pojo.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *  项目启动的时候获取密钥
 */
@Configuration
@Slf4j
@ConditionalOnProperty(prefix = "ly.auth",name = {"clientId","secret"})
public class AuthConfig {
    @Autowired
    private AuthClient authClient;
    @Autowired
    private ClientProperties prop;
    @Bean
    public JwtUtils jwtUtils() throws InterruptedException {
        //一旦失败，需要重新获取密钥，所以用死循环
        while (true) {
            try {
                //获取秘钥
                String key = authClient.getSecretKey(prop.getClientId(), prop.getSecret());
                log.info("获取密钥成功");
                return new JwtUtils(key);
            } catch (Exception e) {
                log.error("获取密钥失败，原因是{},{}秒后进行重试",e.getMessage(),prop.getRetryInterval()/1000);
                //不能重试过于频繁，因此每10重试一次
                Thread.sleep(prop.getRetryInterval());
            }
        }
    }
}
